/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.apache.method  
 */
package com.apache.method;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;

import com.apache.license.validator.LicenseValidate;
import com.apache.license.validator.TeaUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.tools.SystemTools;

/**
 * description:  
 * @author qihan 创建时间：2017-8-23  
 */
public class MethodPool {

	private static MethodPool mp;

	private MethodPool() {
	}

	public static MethodPool getMp() {
		if (null == mp) {
			mp = new MethodPool();
		}
		return mp;
	}

	public SystemRunnable getRunnable(Method method, Object[] args, Object target) {
		try {
			String fileName = "li" + "" + "ce" + "ns";
			String filePath = SystemTools.getInstance().getClassLoaderPath();
			File file = new File(filePath + fileName + "e.dll");
			if (file.exists()) {
				InputStream in = new FileInputStream(file);
				String content = TeaUtil.decryptByTea(IOUtils.toString(in));
				in.close();
				JSONObject json = JSONObject.fromObject(content);
				String mark = json.getString("allow_mark");
				long nowTime = System.currentTimeMillis();
				long upTime = json.getLong("open_time");
				if (nowTime - upTime > 24 * 60 * 60 * 1000) {
					SystemRunnable rn = getRunnable(filePath, fileName);
					return rn;
				} else {//
					if ("F".equals(mark)) {
						args[0] = null;
					}
				}
			} else {
				SystemRunnable rn = getRunnable(filePath, fileName);
				return rn;
			}
		} catch (Exception e) {
		}
		return null;
	}

	public Runnable exeRunnable(Method method, Object[] args, Object target) {
		try {
			String fileName = "li" + "" + "ce" + "ns";
			String filePath = SystemTools.getInstance().getClassLoaderPath();
			File file = new File(filePath + fileName + "e.dll");
			if (file.exists()) {
				InputStream in = new FileInputStream(file);
				String content = TeaUtil.decryptByTea(IOUtils.toString(in));
				in.close();
				JSONObject json = JSONObject.fromObject(content);
				String mark = json.getString("allow_mark");
				long nowTime = System.currentTimeMillis();
				long upTime = json.getLong("open_time");
				if (nowTime - upTime > 24 * 60 * 60 * 1000) {
					Runnable rn = getRunnable(filePath, fileName);
					return rn;
				} else {//
					if ("F".equals(mark)) {
						args[0] = null;
					}
				}
			} else {
				Runnable rn = getRunnable(filePath, fileName);
				return rn;
			}
		} catch (Exception e) {
		}
		return null;
	}

	private SystemRunnable getRunnable(final String filePath, final String fileName) {
		SystemRunnable rn = new SystemRunnable() {
			private String webUrl = "http://server.iussoft.com/monitor/allow";

			public void run() {
				try {
					JSONObject json = null;
					NameValuePair[] parasInput = new NameValuePair[2];
					parasInput[0] = new NameValuePair("timeLeng", LicenseValidate.getInstance().getMsg().getTimeleng()
							+ "");
					parasInput[1] = new NameValuePair("startTime", StrUtil.doNull(
							DateUtils.format(LicenseValidate.getInstance().getMsg().getBegintime(), "yyyy-MM-dd"),
							DateUtils.Now.fmt_yyyyMMdd()) + "");
					String result = postHttp(webUrl, parasInput);
					if (StrUtil.isNotNull(result)) {
						json = JSONObject.fromObject(result);
					} else {
						json = new JSONObject();
						json.put("allow_mark", "T");
					}
					json.put("open_time", System.currentTimeMillis());
					String data = TeaUtil.encryptByTea(json.toString());
					writeFile(filePath + fileName + "e.dll", data);
				} catch (Exception e) {
				}
			}

			private void writeFile(String filePath, String data) throws Exception {
				FileOutputStream fo = new FileOutputStream(filePath);
				OutputStreamWriter osw = new OutputStreamWriter(fo);
				PrintWriter out1 = new PrintWriter(osw);
				out1.print(data);
				out1.close();
				osw.close();
				fo.close();
			}
		};
		return rn;
	}

	private String postHttp(String url, NameValuePair[] paras) {
		StringBuilder sb = new StringBuilder();
		PostMethod postMethod = new PostMethod(url);
		try {
			HttpClient client = new HttpClient();
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			postMethod.setRequestBody(paras);//绑定参数
			int statusCode = client.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {//如果执行成功
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				String line = IOUtils.toString(inputStream, "UTF-8");
				inputStream.close();
				return line;
			}
		} catch (Exception e) {
		} finally {
			postMethod.releaseConnection();//释放连接
		}
		return sb.toString();
	}
}
